import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_class2/3681/accountRelated/CreateAccountPage.dart';
import 'package:flutter_class2/3681/accountRelated/ResetPWPage.dart';
import 'package:flutter_class2/common/global.dart';
import 'package:toast/toast.dart';

import 'MainPage.dart';
import 'accountRelated/account_controller.dart';

class LoginPage extends StatelessWidget {
  Widget build(BuildContext context){
    return LoginPageState();
  }
}

class LoginPageState extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPageState> {

  bool _passwordVisibleFlag = true; // 控制密码是否为明文字符
  String _id = '';//用户名，先初始化一个值，避免后面长度检测出错
  String _password = ""; //密码
  bool _expand = false; //是否展示历史账号
  List<AccountLite> _accountLites = new List(); //历史账号
  GlobalKey _globalKey = new GlobalKey(); //用来标记控件（账号输入的TextField，便于据此调节历史账号的位置、尺寸）

  void initState(){
    super.initState();
    // 进入页面时就获取历史账号列表
    _gainAccountLites();
  }

  @override
  Widget build(BuildContext context) {

    Global global = new Global(); // 控制控件尺寸

    var databaseHelper = new AccountDatabaseHelper(); // 账户控制的数据库

    final logo = Hero(// 创建hero动画，沟通两个组件之间的tag必须统一
      tag: 'headPic',
      child: CircleAvatar(
        backgroundColor: Colors.transparent,
        radius: 48.0,
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(90)),
          child: Image.asset('images/meng.png'),
        ),
      ),
    );

    // 构建单个历史记录item
    Widget _buildItem(AccountLite accountLite) {
      return GestureDetector(
        child: Container(
          child: Flex(
            direction: Axis.horizontal,
            children: <Widget>[
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 5),
                  child: Text(accountLite.id),
                ),
              ),
              GestureDetector(
                child: Padding(
                  padding: EdgeInsets.only(right: 5),
                  child: Icon(
                    Icons.close,
                    color: Colors.black54,
                  ),
                ),
                onTap: () {
                  setState(() {
                    _accountLites.remove(accountLite);
                    SharedPreferenceUtil.delAccountLite(accountLite);
                    //处理最后一个数据，假如最后一个被删掉，将Expand置为false
                    if (!(_accountLites.length > 1 ||
                        _accountLites[0] != AccountLite(_id, _password))) {
                      //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
                      _expand = false;
                    }
                  });
                },
              ),
            ],
          ),
        ),
        onTap: () {
          setState(() {
            _id = accountLite.id;
            _password = accountLite.password;
            _expand = false;
          });
        },
      );
    }

    // 构建历史记录ListView的items
    List<Widget> _buildItems() {
      List<Widget> list = new List();
      for (int i = 0; i < _accountLites.length; i++) {
        if (_accountLites[i] != AccountLite(_id, _password)) {
          //增加账号记录
          list.add(_buildItem(_accountLites[i]));
          //增加分割线
          list.add(Divider(
            color: Colors.black54,
            height: 1,
          )
          );
        }
      }
      if (list.length > 0) {
        list.removeLast(); //删掉最后一个分割线
      }
      return list;
    };

    // 构建历史账号ListView
    Widget _buildListView() {
      if (_expand) {
        List<Widget> children = _buildItems();
        if (children.length > 0) {
          RenderBox renderObject = _globalKey.currentContext.findRenderObject();
          final position = renderObject.localToGlobal(Offset.zero);
          double screenW = MediaQuery.of(context).size.width;
          double currentW = renderObject.paintBounds.size.width;
          double currentH = renderObject.paintBounds.size.height;
          double margin = (screenW - currentW) / 2; // Widget与屏幕的边距
          double offsetY = position.dy;
          double itemHeight = 30.0;
          double dividerHeight = 0.0;
          return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16.0),
              border: Border.all(color: Colors.black54, width: 3.0),
            ),
            child: ListView(
              itemExtent: itemHeight,
              padding: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
              children: children,
            ),
            width: currentW,
            height: (children.length * itemHeight +
                (children.length - 1) * dividerHeight),
            margin: EdgeInsets.fromLTRB(margin, offsetY + currentH + 16, margin, 0),
          );
        }
      }
      return null;
    };

    // 构建账号输入框
    final idTF = TextField(
      key: _globalKey,
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '用户名',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
        suffixIcon: GestureDetector(
          onTap: () {
            //如果个数大于1个或者唯一一个账号跟当前账号不一样才弹出历史账号
            if (_accountLites.length > 1 || _accountLites[0] != AccountLite(_id, _password)) {
              setState(() {
                _expand = !_expand;
              });
            }
          },
          child: _expand
              ? Icon(
            Icons.keyboard_arrow_up,
            color: Colors.black54,
          )
              : Icon(
            Icons.keyboard_arrow_down,
            color: Colors.black54,
          ),
        ),
      ),
      controller: TextEditingController.fromValue(
        TextEditingValue(
          text: _id,
          selection: TextSelection.fromPosition(
            TextPosition(
              affinity: TextAffinity.downstream,
              offset: _id == null ? 0 : _id.length,
            ),
          ),
        ),
      ),
      onChanged: (value){
        _id = value;
      },
    );

    // 构建密码输入框
    final passwordTF = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      obscureText: _passwordVisibleFlag,
      decoration: InputDecoration(
          hintText: '密码',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
          enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
          focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
          suffixIcon: IconButton(
            icon: Icon(_passwordVisibleFlag ? Icons.visibility : Icons.visibility_off),
            color: Colors.black54,
            onPressed: (){
              setState(() {
                _passwordVisibleFlag = !_passwordVisibleFlag;
              });
            },
          )
      ),
      controller: TextEditingController.fromValue(
        TextEditingValue(
          text: _password,
          selection: TextSelection.fromPosition(
            TextPosition(
              affinity: TextAffinity.downstream,
              offset: _password == null ? 0 : _password.length,
            ),
          ),
        ),
      ),
      onChanged: (value){
        _password = value;
      },
    );

    // 构建忘记密码的选项
    final forgotLabel = InkWell(
      child: Text(
        '忘记密码?',
        style: TextStyle(color: Colors.blue,decoration: TextDecoration.underline),
      ),
      onTap: () async {
        Navigator.push(context, MaterialPageRoute(builder: (context)=>ResetPWPage()));
        // 测试数据库用-----------↓
        List accounts;
        print('=== getAllAccounts() ===');
        accounts = await databaseHelper.getAllAccounts();
        accounts.forEach((account) => print(account));
        print('=== getccount(123456) ===');
        Account account = await databaseHelper.getAccount("123456");
        print(account);
        print('=== getccount(12345678) ===');
        Account accoun = await databaseHelper.getAccount("12345678");
        print(accoun.id + " " +accoun.password);
      },
    );

    // 构建注册账户的选项
    final noAccountLabel = InkWell(
      child: Text(
        '没有账号?',
        style: TextStyle(color: Colors.blue,decoration: TextDecoration.underline),
      ),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context)=>CreateAccountPage()));
      },
    );

    // 构建登录按钮
    final loginButton = Hero(
        tag: 'loginButton',
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 16.0),
          child: RaisedButton(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            padding: EdgeInsets.all(12),
            color: Colors.black54,
            child: Text('登录', style: TextStyle(color: Colors.white)),
            onPressed: () async {
              Account account = await databaseHelper.getAccount(_id); // 提取当前账户信息
              if(account != null ){
                if(_password == account.password){
                  Navigator.push(context, MaterialPageRoute(builder: (context)=>MainPage()));

                  Global.currentId = _id; // 临时将当前用户名保存为全局变量
                  Global.currentPhoneNum = account.phoneNum == null ? "" : account.phoneNum;
                  Global.currentEmail = account.email == null ? "" : account.email;
                  Toast.show('用户$_id 登陆成功', context);

                  SharedPreferenceUtil.saveAccountLite(AccountLite(_id, _password));
                  SharedPreferenceUtil.addNoRepeat(_accountLites, AccountLite(_id, _password));
                }else{
                  Toast.show('用户名或密码有误', context);
                }
              }else{
                Toast.show('用户名或密码有误', context);
              }
            },
          ),
        )
    );





    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,// 防止弹出输入法时内容溢出屏幕
      body: Stack(
        children: [
          Center(
              child: Container(
                padding: EdgeInsets.only(left: 24.0, right: 24.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    logo,
                    SizedBox(height: 48.0),
                    idTF,
                    SizedBox(height: 16.0),
                    passwordTF,
                    SizedBox(height: 12.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [forgotLabel, Text(" 或 "), noAccountLabel,],
                    ),
                    loginButton,
                  ],
                ),
              )
          ),
          Offstage(
            child: _buildListView(),
            offstage: !_expand,
          ),
        ],
      )
    );


  }


  // 从sharedpreference获取历史用户
  void _gainAccountLites() async {
    _accountLites.clear();
    _accountLites.addAll(await SharedPreferenceUtil.getAccountLites());
    print(_accountLites);
    // 默认加载第一个账号并填充进账号密码栏
    // if (_accountLites.length > 0) {
    //   _id = _accountLites[0].id;
    //   _password = _accountLites[0].password;
    // }
  }

}